(function () {
  var canvas = document.getElementById("cas");//查找画布
  var ctx = canvas.getContext("2d");//构建环境
  var outcanvas = document.createElement("canvas");//创建画布
  $("#cas").attr("width",$("#cas").parent().width());
  outcanvas.width = canvas.width;//设置宽度
  outcanvas.height = canvas.height;//设置高度
  var octx = outcanvas.getContext('2d');//获得画布上线文
  //console.log($(".right-side").width());

  // audioSource 为音频源，bufferSource为buffer源
  var audioSource, bufferSource;

  //实例化音频对象，音频上下文
  var AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;

  if (!AudioContext) {
    alert("您的浏览器不支持audio API，请更换浏览器（chrome、firefox）再尝试")
    return;
  }

  var AC = new AudioContext();

  // analyser为analysernode，具有频率的数据，用于创建数据可视化
  var analyser = AC.createAnalyser();

  // gain为gainNode，音量处理模块
  var gainnode = AC.createGain();
  gainnode.gain.value = 1;

  //计时器、帧率
  var RAF = (function () {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
      window.setTimeout(callback, 1000 / 60);
    };
  })();

  //播放音乐
  var audio = $(".music-player")[0];//获取音频源

  Date.prototype.Format = function (fmt) { // author: meizz
      var o = {
          "M+": this.getMonth() + 1, // 月份
          "d+": this.getDate(), // 日
          "h+": this.getHours(), // 小时
          "m+": this.getMinutes(), // 分
          "s+": this.getSeconds(), // 秒
          "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
          "S": this.getMilliseconds()
          // 毫秒
      };
      if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1,
              (this.getFullYear() + "")
                  .substr(4 - RegExp.$1.length));
      for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
              fmt = fmt
                  .replace(
                      RegExp.$1,
                      (RegExp.$1.length === 1) ? (o[k])
                          : (("00" + o[k])
                          .substr(("" + o[k]).length)));
      return fmt;
  }

  //默认参数
  var now_time = new Date();
  var default_end_time = now_time.Format("yyyy-MM-dd hh:mm:ss")//获取当前时间作为默认读取数据的结束时间

  var default_start_time = now_time.getTime()-(1000*60*60*24);//前一天作为默认读取数据的开始时间
  now_time.setTime(default_start_time);
  default_start_time = now_time.Format("yyyy-MM-dd hh:mm:ss")
  var default_start_end_time =  default_start_time + ' - ' + default_end_time;

  //音频源数据
  var musics;

  $.post(radio_url,{ time: default_start_end_time },
    function (data) {
      musics = data;
      $(".audioSearch").click(function () {
        var start_end_time = $("#start_end_time").val();
        if (start_end_time == "") {
          alert('请选择时间范围');
        } else {
          $.post(radio_url, { time: start_end_time },
            function (data) {
              musics = data;
              app.render(musics);
              app.bind();
              app.trigger(0);
            },
            'json'
          );
        }
      })

      var nowIndex = 0;   //当前播放到的音乐索引

      var singleLoop = false; //是否单曲循环

      var app = {
        init: function () {
          //初始化，进来自动执行以下函数
          this.render(musics);

          this.bind();

          this.trigger(0);
        },

        bind: function () {
          var that = this;

          audio.onended = function () {//音频播放结束执行
            app.trigger(singleLoop ? nowIndex : (nowIndex + 1));
          };

          /*$(".play-type").on("click", function () {
            singleLoop = !singleLoop;
            $(this).html(singleLoop ? "列表循环" : "单曲循环");
          });*/

          //静音按钮
          $(".muti").on('click', function () {
            var ismuti = !!gainnode.gain.value;
            gainnode.gain.value = ismuti ? 0 : 1;
            $(this).html(ismuti ? "取消静音" : "静音");
          });

          //添加文件，点击后触发文件域点击事件
          /* $(".add-music").on('click', function () {
            $('.music-file').click();
          }); */

          //点击列表后更改音频索引
          $(".music-list").unbind();
          $(".music-list").on("click", "li", function () {
            var index = $(".music-list li").index($(this));
            that.trigger(index);
            var audio_id = musics[index].id;
            /*$.post("test2.php",
              { audioid: audio_id },function(data){//根据ID获取编译结果
                var Compile_text_list = '<div class="Compile_text_list"><span><b>ID:</b><strong>' + audio_id + '</strong></span><p>' + data + '</p></div>';
                $(".Compile_text").prepend(Compile_text_list);
              }
            );*/
          });

          //如果用户选取了自己的音乐则通过filereader读取
          /*$('.music-file').on('change', function () {
            if (this.files.length == 0) return;

            var files = Array.prototype.slice.call(this.files);

            files.forEach(function (file) {
              var fr = new FileReader();
              fr.readAsArrayBuffer(file);//自动读取文件内容
              var mdata = {
                name: file.name.substring(0, file.name.lastIndexOf('.')),//读取文件名
                buffer: null,
                decoding: true
              };

              musics.push(mdata);//将文件信息添加到音频数组末尾

              fr.onload = function (e) {//音频加载完毕触发
                decodeBuffer(e.target.result, function (buffer) {//音频解码方法
                  mdata.buffer = buffer;
                  mdata.decoding = false;
                  $(".music-list li").eq(musics.indexOf(mdata)).html(mdata.name);//将音频名称添加到列表末尾
                })
              };
            });

            that.render(musics);
          });*/
        },

        trigger: function (index) {//触发函数，并传入音频索引
          index = index >= musics.length ? 0 : index;

          //if (musics[index].decoding) return;

          this.stop();

          nowIndex = index;

          $(".music-list li").eq(index).addClass("playing").siblings().removeClass("playing");//给列表里播放的音乐添加样式
          $(".music-list li").eq(index).children("i").addClass("icon-laba").parent().siblings().children("i").removeClass("icon-laba").addClass("icon-jingyin");//给列表里播放的音乐添加样式
          
          if($(".music-list li").length != 0){//滚动滚动条
            var li_left = $(".music-list li").eq(index).position().left - $(".music-contain").width() / 2;
            $(".music-contain").scrollLeft(li_left);
          }

          if (musics[index].src) {
            chooseMusic(musics[index].src);//选择音乐后执行播放操作
          } else if (musics[index].buffer) {
            playMusic(musics[index].buffer);//播放音乐
          }
        },

        stop: function () {
          var ismuti = !!gainnode.gain.value;//获取音量

          if (!ismuti) {//如果音量不为0，则将音量设置为0
            gainnode.gain.value = 0;
          }

          if (!audio.ended || !audio.paused) audio.pause();//停止当前播放的音频

          if (bufferSource && ('stop' in bufferSource)) bufferSource.stop();//？？？

          try {
            if (bufferSource) {
              bufferSource.disconnect(analyser);//断开，分析器节点
              bufferSource.disconnect(AC.destination);//断开音源的输出
            }

            if (audioSource) {
              audioSource.disconnect(analyser);//断开分析器节点
              audioSource.disconnect(AC.destination);//断开音源的输出
            }
          } catch (e) {

          }

          if (!ismuti) {//如果音量为零，则设置为1
            gainnode.gain.value = 1;
          }
        },

        render: function (musics) {
          
          var html = "";
          var music;
          for (var i = 0; i < musics.length; i++) {
            music = musics[i];
            html += '<li title="' + music.name + '" data-audio-id="' + music.id + '"><i class="iconfont icon-jingyin"></i>' + (music.decoding ? "解码中..." : music.id) + '</li>';//将音频数组渲染成列表
          }
          $(".music-list").html("");
          $(".music-list").html(html);
          $(".music-list li").eq(nowIndex).addClass("playing");//为当前播放音频元素添加播放样式
          $(".music-list").width($(".music-list li").length*($(".music-list li").innerWidth()+1)+30);
        }
      };

      //选择audio作为播放源
      function chooseMusic(src) {//传入音频链接
        audio.src = src;
        audio.load();//重新加载音频
        playMusic(audio);
      }

      //对音频buffer进行解码
      /*function decodeBuffer(arraybuffer, callback) {
        AC.decodeAudioData(arraybuffer, function (buffer) {
          callback(buffer);
        }, function (e) {
          alert("文件解码失败")
        })
      }*/

      //音频播放
      function playMusic(arg) {
        var source;
        //如果arg是audio的dom对象，则转为相应的源
        if (arg.nodeType) {//节点类型为正整形
          audioSource = audioSource || AC.createMediaElementSource(arg);
          source = audioSource;
        } else {
          bufferSource = AC.createBufferSource();

          bufferSource.buffer = arg;

          bufferSource.onended = function () {//播放完毕
            app.trigger(singleLoop ? nowIndex : (nowIndex + 1));//播放完毕，音频索引+1
          };

          //播放音频
          setTimeout(function () {
            bufferSource.start()
          }, 0);

          source = bufferSource;
        }

        //连接analyserNode
        source.connect(analyser);

        //再连接到gainNode
        analyser.connect(gainnode);

        //最终输出到音频播放器
        gainnode.connect(AC.destination);
      }

      //绘制音谱的参数
      var rt_array = [];	//用于存储柱形条对象
      var rt_length = 500;		//规定有多少个柱形条
      var grd = ctx.createLinearGradient(0, 110, 0, 270);
      grd.addColorStop(0, "red");
      grd.addColorStop(0.3, "yellow");
      grd.addColorStop(1, "#00E800");

      function showTxt(msg) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.fillStyle = "#FFF";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.font = "20px 微软雅黑";
        ctx.fillText(msg, canvas.width / 2, canvas.height / 2);
        ctx.restore();
      }

      //动画初始化，获取analyserNode里的音频buffer
      function initAnimation() {
        //每个柱形条的宽度，及柱形条宽度+间隔
        var aw = canvas.width / rt_length;
        var w = aw - 0;

        for (var i = 0; i < rt_length; i++) {
          rt_array.push(new Retangle(w, 5, i * aw, canvas.height))
        }

        animate();
      }

      function animate() {
        if (!musics[nowIndex].decoding) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);//掏空一个矩形
          octx.clearRect(0, 0, canvas.width, canvas.height);//掏空一个矩形

          //出来的数组为8bit整型数组，即值为0~256，整个数组长度为1024，即会有1024个频率，只需要取部分进行显示
          var array_length = analyser.frequencyBinCount;
          var array = new Uint8Array(array_length);
          analyser.getByteFrequencyData(array);	//将音频节点的数据拷贝到Uin8Array中
          //数组长度与画布宽度比例
          var bili = array_length / canvas.width;

          for (var i = 0; i < rt_array.length; i++) {
            var rt = rt_array[i];
            //根据比例计算应该获取第几个频率值，并且缓存起来减少计算
            rt.index = ('index' in rt) ? rt.index : ~~(rt.x * bili);
            rt.update(array[rt.index]);
          }

          draw();
        } else {
          showTxt("音频解码中...")
        }

        RAF(animate);
      }

      //制造半透明投影
      function draw() {
        ctx.drawImage(outcanvas, 0, 0);
        //ctx.save();
        //ctx.translate(canvas.width / 2, canvas.height / 2);//重新绘制
        //ctx.rotate(Math.PI);
        //ctx.scale(-1, 1);
        //ctx.drawImage(outcanvas, -canvas.width / 2, -canvas.height / 2);
        //ctx.restore();//清空画板
        //ctx.fillStyle = 'rgba(0, 0, 0, .8)';
        //ctx.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2);
      }

      // 音谱条对象
      function Retangle(w, h, x, y) {
        this.w = w;
        this.h = h; // 小红块高度
        this.x = x;
        this.y = y;
        this.jg = 3;
        this.power = 0;
        this.dy = y; // 小红块位置
        this.num = 0;
      }

      var Rp = Retangle.prototype;

      Rp.update = function (power) {
        this.power = power;
        this.num = ~~(this.power / this.h + 0.5);

        //更新小红块的位置，如果音频条长度高于红块位置，则红块位置则为音频条高度，否则让小红块下降
        var nh = this.dy + this.h;//小红块当前位置
        if (this.power >= this.y - nh) {
          this.dy = this.y - this.power - this.h - (this.power == 0 ? 0 : 1);
        } else if (nh > this.y) {
          this.dy = this.y - this.h;
        } else {
          this.dy += 1;
        }

        this.draw();
      };

      Rp.draw = function () {
        octx.fillStyle = grd;//填充渐变颜色
        var h = (~~(this.power / (this.h + this.jg))) * (this.h + this.jg);
        octx.fillRect(this.x, this.y - h, this.w, h);//绘制已经填充的矩形
        for (var i = 0; i < this.num; i++) {
          var y = this.y - i * (this.h + this.jg);
          octx.clearRect(this.x - 1, y, this.w + 2, this.jg);//掏出一个矩形窟窿
        }
        octx.fillStyle = "#950000";//填充颜色
        octx.fillRect(this.x, ~~this.dy, this.w, this.h);//绘制已经填充的矩形
      };

      app.init();
      initAnimation();

    },
    'json'
  );
}());